//
//  AppDelegate.m
//  DJS
//
//  Created by mac on 2017/12/25.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "LogingViewController.h"
#import "myViewController.h"
#import "workbenchViewController.h"
#import "homeViewController.h"
#import "Home2ViewController.h"
#import "Workbench2ViewController.h"
#import "My2ViewController.h"
#import "WXApi.h"
#import <UserNotifications/UserNotifications.h>
#import <AdSupport/AdSupport.h>
#import "newsViewController.h"
#import "WrittenDocumentsViewController.h"
#import "ReleaseCaseViewController.h"
#import "LegalAdviceViewController.h"
#import "yinDaoYeViewController.h"

#import "SoundViewController.h"
#define NSFoundationVersionNumber_iOS_9_x_Ma
@interface AppDelegate ()<WXApiDelegate,JPUSHRegisterDelegate>
@property(nonatomic,assign)int login;
@property(nonatomic,strong)BaseViewController *viewController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    


    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(networkDidReceiveMessage:) name:@"login" object:nil];
    
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(networkDidReceiveMessage2:) name:@"zhiFu" object:nil];
    

    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(networkDidReceiveMessage3:) name:@"推送" object:nil];
    
    [self getBan];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:nil
                 apsForProduction:true
            advertisingIdentifier:advertisingId];
    
 
    [WXApi registerApp:@"wx7783b1e610d28cbd"];
    
     NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
     NSNumber *waiter_role=[userDic objectForKey:@"waiter_role"];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *getAPPBanben=[ZQTools getAPPBanben];
    
    NSString *getAPPBanben2=[user objectForKey:@"getAPPBanben"];
    
    if (getAPPBanben2==nil ||! [getAPPBanben isEqualToString:getAPPBanben2]) {

        yinDaoYeViewController *yindao=[[yinDaoYeViewController alloc] init];
        UINavigationController *nav1= [[UINavigationController alloc] initWithRootViewController:yindao];
        self.window.rootViewController=nav1;

    }
//    SoundViewController *yindao=[[SoundViewController alloc] init];
//    UINavigationController *nav1= [[UINavigationController alloc] initWithRootViewController:yindao];
//    self.window.rootViewController=nav1;

    
    else{
        if (waiter_role.intValue==0) {
            homeViewController *shouye=[[homeViewController alloc] init];
            
            workbenchViewController *huDong=[[workbenchViewController alloc] init];
            
            myViewController *youJi=[[myViewController alloc] init];
            
            UINavigationController *nav1= [[UINavigationController alloc] initWithRootViewController:shouye];
            UINavigationController *nav2= [[UINavigationController alloc] initWithRootViewController:huDong];
            UINavigationController *nav3= [[UINavigationController alloc] initWithRootViewController:youJi];
            
            nav1.title=@"首页";
            nav2.title=@"工作台";
            nav3.title=@"我的";
            
            [nav1.tabBarItem setSelectedImage:[UIImage imageNamed:@"首页1"]];
            [nav1.tabBarItem setImage:[UIImage imageNamed:@"首页"]];
            
            [nav2.tabBarItem setSelectedImage:[UIImage imageNamed:@"工作台1"]];
            [nav2.tabBarItem setImage:[UIImage imageNamed:@"工作台"]];
            
            [nav3.tabBarItem setSelectedImage:[UIImage imageNamed:@"我的1"]];
            [nav3.tabBarItem setImage:[UIImage imageNamed:@"我的"]];
            
            [[UITabBar appearance] setTintColor:_backgroundColor];
            
            UITabBarController *bar=[[UITabBarController alloc] init];
            bar.viewControllers=@[nav1,nav2,nav3];
            
            self.window.rootViewController=bar;
            [self.window makeKeyAndVisible];
        }
        else{
            Home2ViewController *shouye=[[Home2ViewController alloc] init];
            Workbench2ViewController *huDong=[[Workbench2ViewController alloc] init];
            
            My2ViewController *youJi=[[My2ViewController alloc] init];
            
            UINavigationController *nav1= [[UINavigationController alloc] initWithRootViewController:shouye];
            UINavigationController *nav2= [[UINavigationController alloc] initWithRootViewController:huDong];
            UINavigationController *nav3= [[UINavigationController alloc] initWithRootViewController:youJi];
            
            nav1.title=@"首页";
            nav2.title=@"工作台";
            nav3.title=@"我的";
            
            [nav1.tabBarItem setSelectedImage:[UIImage imageNamed:@"首页1"]];
            [nav1.tabBarItem setImage:[UIImage imageNamed:@"首页"]];
            
            [nav2.tabBarItem setSelectedImage:[UIImage imageNamed:@"工作台1"]];
            [nav2.tabBarItem setImage:[UIImage imageNamed:@"工作台"]];
            
            [nav3.tabBarItem setSelectedImage:[UIImage imageNamed:@"我的1"]];
            [nav3.tabBarItem setImage:[UIImage imageNamed:@"我的"]];
            
            [[UITabBar appearance] setTintColor:_backgroundColor];
            
            UITabBarController *bar=[[UITabBarController alloc] init];
            bar.viewControllers=@[nav1,nav2,nav3];
            
            self.window.rootViewController=bar;
            [self.window makeKeyAndVisible];
        }
        
    
    }
    return YES;
}
-(void)getBan{
    NSString *edition_num=[ZQTools getAPPBanben];
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:edition_num,@"edition_num", nil];
    [ZQTools AFNPostDataUrl:@"waiter/check/is_alipay" Dict:dic andTableView:nil andViewController:nil andSuccessBlock:^(id responseObject) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:responseObject forKey:@"isOrSH"];
        
    } anderrorBlock:nil];
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)onResp:(BaseResp *)resp {
    if (_login==1) {
        _login=0;
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode== 0) {
            NSString *code = aresp.code;
            [self getWechatAccessTokenWithCode:code];
        }
    }
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"DJS"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

-(void)networkDidReceiveMessage:(NSNotification *)notification{
    _login=1;
    
}

-(void)networkDidReceiveMessage2:(NSNotification *)notification{
    _login=2;
    
    
}
- (void)getWechatAccessTokenWithCode:(NSString *)code
{
    
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",
                    @"wx7783b1e610d28cbd",@"6bdde6b837f9d297a5ae14ce924d704c",code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers error:nil];
                
                NSString *accessToken = dic[@"access_token"];
                NSString *openId = dic[@"openid"];
                NSLog(@"%@",accessToken);
                [self getWechatUserInfoWithAccessToken:accessToken openId:openId];
            }
        });
    });
}

- (void)getWechatUserInfoWithAccessToken:(NSString *)accessToken openId:(NSString *)openId
{
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers error:nil];
                
                NSNotification * notice = [NSNotification notificationWithName:@"abc" object:nil userInfo:dic];
                //发送消息
                [[NSNotificationCenter defaultCenter]postNotification:notice];
            }
        });
        
    });
}

// NS_DEPRECATED_IOS(3_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and -[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications")



// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    else {
        // 本地通知
    }
    
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段，key是自己定义的
    NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);
    
    NSLog(@"%@",userInfo);
   
   
    NSNumber *mu_services_id=[userInfo objectForKey:@"mu_services_id"];
    NSNumber *message_type=[userInfo objectForKey:@"mu_services_type"];
    NSNumber *mu_services_type=[userInfo objectForKey:@"mu_services_type"];

    if ([mu_services_id isKindOfClass:[NSNull class]]&&message_type.intValue==0) {
        NewsViewController *news=[[NewsViewController alloc] init];
        news.message_type=@"0";
        [ZQTools pushNextViewController:_viewController  andRootController:news];
    }else{
        if(![mu_services_id isKindOfClass:[NSNull class]]&&mu_services_type.intValue==1){
            WrittenDocumentsViewController *controller=[[WrittenDocumentsViewController alloc] init];
            controller.document_id=mu_services_id;
            [ZQTools pushNextViewController:self.viewController  andRootController:controller];
        }else if(![mu_services_id isKindOfClass:[NSNull class]]&&mu_services_type.intValue==2){
            WrittenDocumentsViewController *controller=[[WrittenDocumentsViewController alloc] init];
            controller.document_id=mu_services_id;
            [ZQTools pushNextViewController:self.viewController  andRootController:controller];
        }   else if(![mu_services_id isKindOfClass:[NSNull class]]&&mu_services_type.intValue==3){
            NSDictionary *typeDic=[NSDictionary dictionaryWithObjectsAndKeys:mu_services_id,@"litigation_id", nil];
            ReleaseCaseViewController *controller=[[ReleaseCaseViewController alloc] init];
            controller.dic=typeDic;
            [ZQTools pushNextViewController:self.viewController  andRootController:controller];
        }  else if(![mu_services_id isKindOfClass:[NSNull class]]&&mu_services_type.intValue==0){
            LegalAdviceViewController *controller=[[LegalAdviceViewController alloc] init];
            controller.consult_id=mu_services_id;
            [ZQTools pushNextViewController:self.viewController  andRootController:controller];
        }
    }
    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
     completionHandler();  // 系统要求执行这个方法
    
}
-(void)networkDidReceiveMessage3:(NSNotification *)notification{
    
    NSDictionary *dic=notification.userInfo;
    _viewController=[dic objectForKey:@"viewController"];
}



@end
